package com.spring.framework.transaction.example;

import com.spring.framework.transaction.model.TxStudy;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.transaction.support.DefaultTransactionStatus;

import javax.annotation.Resource;

/**
 * @author xuweizhi
 * @since 2021/08/03 14:10
 */
@Component
@SuppressWarnings("all")
public class DeclarativeTransaction {

	@Resource
	private TxStudyService txStudyService;

	@Resource
	private JdbcTemplate jdbcTemplate;

	public void testTx() {
		TxStudy txStudy = this.getTxStudy((long) 1);
		System.out.println(txStudy);
		this.insertTxStudy(new TxStudy("insertTxStudy", 23));
	}

	@Transactional(readOnly = true, timeout = 30)
	public TxStudy getTxStudy(Long id) {
		DefaultTransactionStatus transactionStatus = (DefaultTransactionStatus) TransactionAspectSupport.currentTransactionStatus();
		System.out.println("getTxStudy method Transaction isReadOnly: " + transactionStatus.isReadOnly());
		String sql = "select * from tx_study where id = ?";
		return jdbcTemplate.queryForObject(sql, BeanPropertyRowMapper.newInstance(TxStudy.class), id);
	}

	public void insertTxStudy(TxStudy txStudy) {
		DefaultTransactionStatus transactionStatus = (DefaultTransactionStatus) TransactionAspectSupport.currentTransactionStatus();
		System.out.println("insertTxStudy method Transaction isReadOnly: " + transactionStatus.isReadOnly());
		String sql = "insert into tx_study (name,age) values (?,?)";
		jdbcTemplate.update(sql, txStudy.getName(), txStudy.getAge());
	}

}
